package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityVideoCompressBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaMetadataInfo;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoCompressActivity extends BaseAc<ActivityVideoCompressBinding> {

    public static String videoPath = "";
    private int width, height;
    private int bitrate;
    private String format = "";

    private long videoLength = 0;

    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_compress;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivVideoCompressBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivVideoCompressSave.setOnClickListener(this);
        mDataBinding.tvCompressVideo.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvCompressVideo://开始压缩
                videoCompress(width * mDataBinding.sbFbl.getProgress() / 100, height * mDataBinding.sbFbl.getProgress() / 100, bitrate * mDataBinding.sbBitrate.getProgress() / 100);
                break;
            case R.id.ivVideoCompressSave://保存
                saveVideo();
                break;
        }
    }

    @Override
    protected void initData() {
        videoLength = MediaUtil.getDuration(videoPath);
        setPlayer();

        RxUtil.create(new RxUtil.Callback<MediaMetadataInfo>() {
            @Override
            public void doBackground(ObservableEmitter<MediaMetadataInfo> emitter) {
                MediaMetadataInfo mediaMetadataInfo = MediaUtil.getMediaMetadataInfo(videoPath);
                emitter.onNext(mediaMetadataInfo);
            }

            @Override
            public void accept(MediaMetadataInfo info) {
                if (info != null) {
                    width = info.getWidth();
                    height = info.getHeight();
                    bitrate = info.getBitrate();
                }
            }
        });
        String fileName = FileUtils.getFileName(videoPath);
        int i = fileName.lastIndexOf(".");
        format = fileName.substring(i, fileName.length());
    }

    //保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, videoPath);//保存到手机相册
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_suc));
                    }

                    @Override
                    public void accept(String obj) {

                    }
                });
            }
        }, 1000);
    }

    //压缩视频
    private void videoCompress(int width, int height, int bitrate) {
        EditorHolder.editor().videoCompress(videoPath, width, height, bitrate, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.video_compress_suc));
                String filePath = FileUtil.generateFilePath(Content.myTemp, format);
                FileUtils.copy(outFilePath, filePath);
                videoPath = outFilePath;
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                mDataBinding.videoView.setVideoPath(videoPath);
                mDataBinding.videoView.seekTo(1);
                mDataBinding.videoView.start();
                startTime();
            }

            @Override
            public void onFailure(String errMsg) {
                ToastUtils.showShort(getString(R.string.video_compress_def));
                dismissDialog();
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.video_compress_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }


    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

}